from selenium import webdriver
import time
from PIL import Image
import requests
import re
import json
from selenium.webdriver.common.action_chains import ActionChains
import datetime
import os
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions


def getTracks(distance):
    # 先均加速后均减速模拟
    tracks = []
    offset = 0
    turn_dis = distance * 4 / 5
    t = 0.4
    v = 0
    while offset < distance:
        if offset < turn_dis:
            a = 2
        else:
            a = -3
        v0 = v
        v = v0 + a * t
        move_dis = v0 * t + 1 / 2 * a * t * t
        offset += move_dis
#         print(move_dis)
        tracks.append(round(move_dis))
    return tracks

def getImgDistance(name):
    img=Image.open(f"./easygo/image/{name}.jpg")
    _break=False
    for i in range(400, img.size[0]-45):
        if _break:
            break
        for j in range(img.size[1]-45):
            #s为白边总和，s2为白边之内灰色总和
            s=0
            s2=0
            for m in range(1,26):
                s=s+sum(img.getpixel((i,j+m)))+sum(img.getpixel((i+m,j)))
                s2=s2+sum(img.getpixel((i+1,j+m)))+sum(img.getpixel((i+m,j+1)))
            #阈值为测试结果
            if s>=35000 and s2<=15000:
                  #调试代码
#                 box=(i,j,i+28,j+28)
#                 region=img1.crop(box)
#                 plt.figure()
#                 plt.imshow(region)
#                 print(i,j)
                _break=True
                break
    saveDistance(name,i-1)
    return i-1

def getDistance(name,url):
    with open('./easygo/image/distance.json') as f:
        _dict=json.load(f)
    try:
        distance=_dict[name]
    except:
        picture=requests.get(url)
        #保存文件
        open(f"./easygo/image/{name}.jpg",'wb').write(picture.content)
        distance=getImgDistance(name)
    return distance


def calculateNarrowDistance(distance,left):
    ratio=0.485
    distance_narrow=(distance-20)*ratio-left
    return distance_narrow

def saveDistance(name,distance):
    with open('./easygo/image/distance.json','r') as f:
        _dict=json.load(f)
    f.close()
    _dict[name]=distance
    with open('./easygo/image/distance.json','w') as f:
        json.dump(_dict,f)
    f.close()
    # print('saveDistance ok')


def login(qqlist):
    today = datetime.datetime.now().strftime("%Y%m%d")
    print(f'开始登陆，获取cookie,qq号码：{qqlist}')
    write_log(f'开始登陆，获取cookie,qq号码：{qqlist}',f'selenium_log{today}.log',content_only = False)
    mobileEmulation = {'deviceName': 'Galaxy S5'}
    options = webdriver.ChromeOptions()
    options.add_experimental_option('mobileEmulation', mobileEmulation)
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    browser = webdriver.Chrome(options=options)
    browser.delete_all_cookies()
    # 打开qq空间
    browser.get("http://i.qq.com")
    browser.implicitly_wait(20)
    # 输入账号密码
    browser.find_element_by_xpath('//*[@id="u"]').send_keys(qqlist[0])
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="p"]').send_keys(qqlist[1])
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="go"]').click()
    browser.implicitly_wait(30)
    # 转到验证码iframe
    try:
        browser.switch_to.frame('tcaptcha_iframe')
        time.sleep(1)
    except:
        now=datetime.datetime.now()
        browser.save_screenshot(f'./image_logs/{now}.png')
        browser.close()
        print(f'login 出现错误！')
        write_log(f'{qqlist}:{browser.page_source}',f'selenium_log{today}.log',content_only = False)
        return 'nothing'

    notstop=True
    while notstop:
        try:
            # 获取图片url
            url = browser.find_element_by_xpath('//*[@id="slideBg"]').get_attribute('src')
            name = re.findall(r'(hycdn.*)\?', url)[0]
            # 小滑块的左侧距离
            left_get = browser.find_element_by_xpath('//*[@id="slideBlock"]').get_attribute('style')
            left = int(re.findall(r'left\: (\d*)px', left_get)[0])
            # 控制块
            slider = browser.find_element_by_id('tcaptcha_drag_button')
            # slider=browser.find_element_by_xpath('//*[@id="tcaptcha_drag_thumb"]')
            notstop=False
        except Exception as e:
            print(e)
            time.sleep(1)


    distance = getDistance(name, url)
    distance_narrow = calculateNarrowDistance(distance, left)
    tracks = getTracks(int(distance_narrow))

    action = ActionChains(browser)
    # 按住滑块不放
    action.click_and_hold(slider)
    # action.reset_actions()
    for track in tracks:
        action.move_by_offset(xoffset=track, yoffset=0)
    action.release().perform()
    # print('ok')



    try:
        WebDriverWait(browser, 30, 0.5).until(expected_conditions.presence_of_element_located((By.ID, "nav_bar_me")))
        judge=browser.find_element_by_id('nav_bar_me')
        cookie = {}
        for i in browser.get_cookies():
            cookie[i["name"]] = i["value"]
        print(cookie)
        browser.close()
        return cookie
    except:
        now=datetime.datetime.now()
        browser.save_screenshot(f'./image_logs/{now}.png')
        print(f'login 出现错误！')
        write_log(f'{qqlist}:{browser.page_source}',f'selenium_log{today}.log',content_only = False)
        return 'nothing'

def write_log(content = None, logfilename = 'selenium_log.log', content_only = False):
    if content is not None and 0 < len( content ):
        today = datetime.datetime.now().strftime("%Y%m%d")
        if logfilename is None:
            logfilename = f"easygo{today}.log"
        try:
            with open( os.path.join(f'./logs/',logfilename ),'a',encoding='utf-8') as f:
                if content_only:
                    info = f"{str(content)}\n"
                else:
                    info = f"[{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}] {content}\n"
                f.write(info)
            return 1
        except Exception as ex:
            return 0
    return -1

